# backend/main.py
from fastapi import FastAPI, Response
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.responses import JSONResponse  # 添加JSONResponse
from .database import engine
from .models import Base
from .routers import (
    auth_router,
    admin_router,
    library_router,
    book_router,
    borrow_router
)

# 创建所有表
Base.metadata.create_all(bind=engine)

app = FastAPI(
    title="小学同学共享图书APP",
    version="1.0.0",
    # 设置默认响应类
    default_response_class=JSONResponse
)


# 添加编码中间件
@app.middleware("http")
async def add_charset_header(request, call_next):
    """添加 UTF-8 字符集到响应头"""
    response = await call_next(request)
    content_type = response.headers.get("Content-Type", "")

    # 确保 JSON 响应有正确的字符集
    if "application/json" in content_type and "charset" not in content_type:
        response.headers["Content-Type"] = "application/json; charset=utf-8"

    return response


# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 压缩响应
app.add_middleware(GZipMiddleware, minimum_size=1000)

# 包含路由
app.include_router(auth_router.router, prefix="/api/auth", tags=["认证"])
app.include_router(admin_router.router, prefix="/api/admin", tags=["管理员"])
app.include_router(library_router.router, prefix="/api/library", tags=["书阁"])
app.include_router(book_router.router, prefix="/api/book", tags=["图书"])
app.include_router(borrow_router.router, prefix="/api/borrow", tags=["借阅"])


@app.get("/", response_class=JSONResponse)  # 显式设置响应类
def read_root():
    return {"message": "小学同学共享图书APP后端服务"}